{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# High-level CNTK Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import os\n",
    "import sys\n",
    "import cntk\n",
    "from cntk.layers import Convolution2D, MaxPooling, Dense, Dropout\n",
    "from common.params import *\n",
    "from common.utils import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Force one-gpu\n",
    "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OS:  linux\n",
      "Python:  3.5.2 |Anaconda custom (64-bit)| (default, Jul  2 2016, 17:53:06) \n",
      "[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]\n",
      "Numpy:  1.14.1\n",
      "CNTK:  2.4\n",
      "GPU:  ['Tesla P100-PCIE-16GB', 'Tesla P100-PCIE-16GB']\n",
      "CUDA Version 8.0.61\n",
      "CuDNN Version  6.0.21\n"
     ]
    }
   ],
   "source": [
    "print(\"OS: \", sys.platform)\n",
    "print(\"Python: \", sys.version)\n",
    "print(\"Numpy: \", np.__version__)\n",
    "print(\"CNTK: \", cntk.__version__)\n",
    "print(\"GPU: \", get_gpu_name())\n",
    "print(get_cuda_version())\n",
    "print(\"CuDNN Version \", get_cudnn_version())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def create_symbol(n_classes=N_CLASSES):\n",
    "    # Weight initialiser from uniform distribution\n",
    "    # Activation (unless states) is None\n",
    "    with cntk.layers.default_options(init = cntk.glorot_uniform(), activation = cntk.relu):\n",
    "        x = Convolution2D(filter_shape=(3, 3), num_filters=50, pad=True)(features)\n",
    "        x = Convolution2D(filter_shape=(3, 3), num_filters=50, pad=True)(x)\n",
    "        x = MaxPooling((2, 2), strides=(2, 2), pad=False)(x)\n",
    "        x = Dropout(0.25)(x)\n",
    "\n",
    "        x = Convolution2D(filter_shape=(3, 3), num_filters=100, pad=True)(x)\n",
    "        x = Convolution2D(filter_shape=(3, 3), num_filters=100, pad=True)(x)\n",
    "        x = MaxPooling((2, 2), strides=(2, 2), pad=False)(x)\n",
    "        x = Dropout(0.25)(x)    \n",
    "        \n",
    "        x = Dense(512)(x)\n",
    "        x = Dropout(0.5)(x)\n",
    "        x = Dense(n_classes, activation=None)(x)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def init_model(m, labels, lr=LR, momentum=MOMENTUM):\n",
    "    # Loss (dense labels); check if support for sparse labels\n",
    "    loss = cntk.cross_entropy_with_softmax(m, labels)  \n",
    "    # Momentum SGD\n",
    "    # https://github.com/Microsoft/CNTK/blob/master/Manual/Manual_How_to_use_learners.ipynb\n",
    "    # unit_gain=False: momentum_direction = momentum*old_momentum_direction + gradient\n",
    "    # if unit_gain=True then ...(1-momentum)*gradient\n",
    "    learner = cntk.momentum_sgd(m.parameters,\n",
    "                                lr=cntk.learning_rate_schedule(lr, cntk.UnitType.minibatch) ,\n",
    "                                momentum=cntk.momentum_schedule(momentum), \n",
    "                                unit_gain=False)\n",
    "    trainer = cntk.Trainer(m, (loss, cntk.classification_error(m, labels)), [learner])\n",
    "    return trainer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preparing train set...\n",
      "Preparing test set...\n",
      "(50000, 3, 32, 32) (10000, 3, 32, 32) (50000, 10) (10000, 10)\n",
      "float32 float32 float32 float32\n",
      "CPU times: user 671 ms, sys: 576 ms, total: 1.25 s\n",
      "Wall time: 1.25 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Data into format for library\n",
    "x_train, x_test, y_train, y_test = cifar_for_library(channel_first=True, one_hot=True)\n",
    "# CNTK format\n",
    "y_train = y_train.astype(np.float32)\n",
    "y_test = y_test.astype(np.float32)\n",
    "print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)\n",
    "print(x_train.dtype, x_test.dtype, y_train.dtype, y_test.dtype)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 24 ms, sys: 32 ms, total: 56 ms\n",
      "Wall time: 69 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Placeholders\n",
    "features = cntk.input_variable((3, 32, 32), np.float32)\n",
    "labels = cntk.input_variable(N_CLASSES, np.float32)\n",
    "# Load symbol\n",
    "sym = create_symbol()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 119 ms, sys: 116 ms, total: 235 ms\n",
      "Wall time: 236 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "trainer = init_model(sym, labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1  |  Accuracy: 0.468750\n",
      "Epoch 2  |  Accuracy: 0.640625\n",
      "Epoch 3  |  Accuracy: 0.609375\n",
      "Epoch 4  |  Accuracy: 0.578125\n",
      "Epoch 5  |  Accuracy: 0.812500\n",
      "Epoch 6  |  Accuracy: 0.781250\n",
      "Epoch 7  |  Accuracy: 0.671875\n",
      "Epoch 8  |  Accuracy: 0.843750\n",
      "Epoch 9  |  Accuracy: 0.796875\n",
      "Epoch 10  |  Accuracy: 0.843750\n",
      "CPU times: user 40.3 s, sys: 13.1 s, total: 53.3 s\n",
      "Wall time: 53.2 s\n"
     ]
    }
   ],
   "source": [
    "%%time \n",
    "# Main training loop: 53s\n",
    "for j in range(EPOCHS):\n",
    "    for data, label in yield_mb(x_train, y_train, BATCHSIZE, shuffle=True):\n",
    "        trainer.train_minibatch({features: data, labels: label})\n",
    "    # Log (this is just last batch in epoch, not average of batches)\n",
    "    eval_error = trainer.previous_minibatch_evaluation_average\n",
    "    print(\"Epoch %d  |  Accuracy: %.6f\" % (j+1, (1-eval_error)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 291 ms, sys: 88.9 ms, total: 379 ms\n",
      "Wall time: 408 ms\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Main evaluation loop: 343ms\n",
    "n_samples = (y_test.shape[0]//BATCHSIZE)*BATCHSIZE\n",
    "y_guess = np.zeros(n_samples, dtype=np.int)\n",
    "y_truth = np.argmax(y_test[:n_samples], axis=-1)\n",
    "c = 0\n",
    "for data, label in yield_mb(x_test, y_test, BATCHSIZE):\n",
    "    predicted_label_probs = sym.eval({features : data})\n",
    "    y_guess[c*BATCHSIZE:(c+1)*BATCHSIZE] = np.argmax(predicted_label_probs, axis=-1)\n",
    "    c += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy:  0.7701322115384616\n"
     ]
    }
   ],
   "source": [
    "print(\"Accuracy: \", 1.*sum(y_guess == y_truth)/len(y_guess))"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
